<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 搜索条件 -->
      <el-form-item label="行业名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['eye:industry:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['eye:industry:edit']">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['eye:industry:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格列表 -->
    <el-table id="tableDiv" :height="tableHeight" v-loading="loading" border :data="industryList" @sort-change="handleSortChange" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="行业名称" sortable="custom" align="center" prop="name">
        <template slot-scope="scope">
          <el-tag :type="scope.row.classStyle">{{ scope.row.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" sortable="custom" align="center" prop="sortNum"/>
      <el-table-column label="操作" width="200" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['eye:industry:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['eye:industry:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页-->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改股票行业对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="行业名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入行业名称"/>
        </el-form-item>
        <el-form-item label="回显样式" prop="classStyle">
          <el-select v-model="form.classStyle">
            <el-option
              v-for="item in listClassOptions"
              :key="item.value"
              :label="item.label + '(' + item.value + ')'"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listIndustry, getIndustry, delIndustry, addIndustry, updateIndustry } from '../../../api/eye/industry'
import Sortable from 'sortablejs'
import { batchUpdateStockIndustry } from '../../../api/eye/industry'

export default {
  name: 'Industry',
  data() {
    return {
      tableHeight: 200,
      // 上传参数
      uploadParam: {},
      // 遮罩层
      loading: true,
      // 数据标签回显样式
      listClassOptions: [
        {
          value: 'blue',
          label: '蓝色妖姬'
        },
        {
          value: 'red',
          label: '红红火火'
        },
        {
          value: 'green',
          label: '绿色'
        },
        {
          value: 'yellow',
          label: '金碧辉煌'
        },
        {
          value: 'purple',
          label: '紫气东来'
        }
      ],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 股票行业表格数据
      industryList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        sortNum: null,
        stockCode: null,
        name: null,
        classStyle: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  mounted() {
    this.getTableMaxHeight()
    this.initSortable()
  },
  created() {
    this.getList()
  },
  methods: {
    //获取容器当前高度，重设表格的最大高度
    getTableMaxHeight() {
      this.$nextTick(function() {
        let t = document.querySelector('#tableDiv')
        console.log('行业 重置高度')
        if (t == null) return
        this.tableHeight = window.innerHeight - t.getBoundingClientRect().top - 75
      })
    },
    initSortable() {
      //将el-table变为可拖拽的
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const t = this
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {

          let dragBeforeArray = JSON.parse(JSON.stringify(t.industryList))
          let dragBeforeSortNum = dragBeforeArray.map(item => item.sortNum)

          console.log('拖动前所有数据:')
          console.log(JSON.stringify(dragBeforeArray))
          console.log('拖动前顺序:')
          console.log(dragBeforeSortNum)

          let dragAfterArray = []
          console.log('拖动前下标:' + oldIndex)
          console.log('拖动后下标:' + newIndex)
          console.log(dragBeforeArray)
          dragBeforeArray.splice(
            newIndex,
            0,
            dragBeforeArray.splice(oldIndex, 1)[0]
          )

          dragAfterArray = JSON.parse(JSON.stringify(dragBeforeArray))
          console.log('拖动后所有数据:')
          console.log(dragAfterArray)

          t.industryList = []
          t.$nextTick(function() {
            t.industryList = dragAfterArray
          })

          let update = []
          for (let i = 0; i < dragAfterArray.length; i++) {
            dragAfterArray[i].sortNum = dragBeforeSortNum[i]
            update.push({ id: dragAfterArray[i].id, sortNum: dragBeforeSortNum[i] })
          }

          console.log('拖动更新数据:')
          console.log(JSON.stringify(update))

          batchUpdateStockIndustry(update).then(res => {
            t.$modal.msgSuccess(res.msg)
          })

        },
        // 元素被选中
        onChoose: function(/**Event*/evt) {
          console.log('选中元素:')
          console.log(evt)
          evt.oldIndex  // element index within parent
        }

      })
    },
    /** 查询股票行业列表 */
    getList() {
      this.loading = true
      listIndustry(this.queryParams).then(response => {
        this.industryList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 排序
    handleSortChange(column, prop, order) {
      console.log('排序')
      // 排序字段
      let sortColumn = column.prop
      // 升序还是降序
      let sortOrder = column.order
      this.queryParams.orderByColumn = sortColumn
      if (sortOrder === 'ascending') {
        this.queryParams.isAsc = 'asc'
      } else {
        this.queryParams.isAsc = 'desc'
      }
      this.getList()
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sortNum: null,
        name: null,
        classStyle: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加股票行业'
      this.form.classStyle = 'blue'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getIndustry(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改股票行业'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateIndustry(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addIndustry(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除？').then(function() {
        return delIndustry(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    }
  }
}
</script>

<style scoped>
.el-tag.el-tag--yellow {
  background-color: #fff8e6;
  border-color: #fff1cc;
  color: #ffba00;
}

.el-tag.el-tag--red {
  background-color: #ffeded;
  border-color: #ffdbdb;
  color: #ff4949;
}

.el-tag.el-tag--blue {
  background-color: #e8f4ff;
  border-color: #d1e9ff;
  color: #1890ff;
}

.el-tag.el-tag--purple {
  background-color: #ec97ec;
  border-color: #ec97ec;
  color: purple;
}

.el-tag.el-tag--green {
  background-color: #e7faf0;
  border-color: #d0f5e0;
  color: #13ce66;
}
</style>
